package com.wyq.new_springboot.controller;

import com.alibaba.druid.util.StringUtils;
import com.wyq.new_springboot.util.result.Result;
import com.wyq.new_springboot.util.result.ResultCode;
import com.wyq.new_springboot.util.result.ResultGenerator;
import io.netty.util.internal.StringUtil;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.support.DefaultMultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.Month;
import java.time.ZoneOffset;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

/**
 * 文件管理
 * @Author weiyaqiang
 * @create 2021/4/7 14:40
 */
@Controller
@RequestMapping("/file")
public class FileController {

    @Value("${file.path}")
    private String filePath;
    /**
     * 跳转到文件管理的主页
     * @return
     */
    @RequiresRoles("admin")
    @RequestMapping("/index")
    public String toHtml(){
        return "fileManage";
    }

    @RequestMapping("/download")
    @ResponseBody
    public Result download(HttpServletRequest request, HttpServletResponse response){
        String fileName = "a.txt";// 文件名
        if (fileName != null) {
            //设置文件路径
            File file = new File("E:\\upload\\2021\\4\\8\\a.txt");
            if (file.exists()) {
                response.setContentType("application/force-download");// 设置强制下载不打开
                response.addHeader("Content-Disposition", "attachment;fileName=" + fileName);// 设置文件名
                byte[] buffer = new byte[1024];
                FileInputStream fis = null;
                BufferedInputStream bis = null;
                try {
                    fis = new FileInputStream(file);
                    bis = new BufferedInputStream(fis);
                    OutputStream os = response.getOutputStream();
                    int i = bis.read(buffer);
                    while (i != -1) {
                        os.write(buffer, 0, i);
                        i = bis.read(buffer);
                    }
                    return ResultGenerator.genSuccessResult();
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    if (bis != null) {
                        try {
                            bis.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    if (fis != null) {
                        try {
                            fis.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
        return ResultGenerator.genFailResult(ResultCode.FAIL,"下载失败");
    }

    /**
     * 文件上传的处理
     * @param request
     * @return
     */
    @RequestMapping(value = "/upload",method = RequestMethod.POST)
    @ResponseBody
    public Result  update(HttpServletRequest request){
        MultipartHttpServletRequest request1= (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap =request1.getFileMap();
        //遍历map
        Set<String> strings = fileMap.keySet();
        for (String s:strings) {
            MultipartFile multipartFile = fileMap.get(s);
            String originalFilename = multipartFile.getOriginalFilename();
            //获取文件后缀名
            String substring = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
            //获取日期
            LocalDateTime localDateTime=LocalDateTime.now();
            int year = localDateTime.getYear();
            int month = localDateTime.getMonthValue();
            int day = localDateTime.getDayOfMonth();
            //获取时间戳
            long l = localDateTime.toInstant(ZoneOffset.of("+8")).toEpochMilli();
            //定义路径
            String path="/"+year+"/"+month+"/"+day+"/"+l+originalFilename;
            File file=new File(filePath+path);
            try {
//                int s2=1/0;//测试异常
                file.mkdirs();
                multipartFile.transferTo(file);//上传文件
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return ResultGenerator.genSuccessResult();
    }
}
